package org.cu.ooad.finalproject.layar;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Logger;

import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONObject;

public class MapAdapter {

	private final static Logger log = Logger.getLogger(MapAdapter.class
			.getName());

	public MapAdapter() {
		super();
	}

	public String getPOIAddress(POI poi) {
		
		try {
			URL url = new URL(
					"http://maps.googleapis.com/maps/api/geocode/json?latlng="
							+ poi.getLat() + "," + poi.getLon()
							+ "&sensor=true");
			URLConnection connection = url.openConnection();
			connection.addRequestProperty("Referer", "http://cucampusmaplayer"
					+ ".appspot.com");

			String line;
			StringBuilder builder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}

			JSONObject json = new JSONObject(builder.toString());
			log.warning(json.toString());
			
			String status = json.getString("status");
			if (status==null || !status.equals("OK")) {
				return null;
			}
			
			JSONArray results = json.getJSONArray("results");
			JSONObject tempResult = null;
			String address = null;
			for (int i=0; i<results.length(); i++) {
				tempResult = (JSONObject) results.get(0);
				address = tempResult.getString("formatted_address");
				if (address != null) {
					return address;
				}
			}

		} catch (Exception e) {
			log.warning("Error while constructing address: " + e.getMessage());
		}

		return null;
	}

}
